#include "TelegramDispatcher.h"
#include <SFML/System.hpp>
#include "BasePlayer.h"
#include "PlayerManager.h"


void TelegramDispatcher::DispatchTelegram(int sender, int receiver, int msg, float delayTime, const void* param)
{
	Telegram tel(sender, receiver, msg, delayTime, param);
	if (delayTime <= 0.f)			//Dispatch msg now
	{
		BasePlayer* pReceiver = PlayerManager::Istance()->GetEntityByID(receiver);
		Discharge(pReceiver, tel);
	} 
	else							//wait the delay
	{
		sf::Clock clock;
		tel.DispatchTime = clock.GetElapsedTime() + delayTime;
		PriorityQueue.insert(tel);
	}
}

void TelegramDispatcher::Discharge(BasePlayer *receiver, Telegram telegram)
{
	receiver->HandleMessage(telegram);
}

void TelegramDispatcher::DispatchQueuedMessages()
{
	sf::Clock clock;
	float time =  clock.GetElapsedTime();

	while(PriorityQueue.begin()->DispatchTime < time)
	{
		Telegram tel = *PriorityQueue.begin();

		BasePlayer* receiver = PlayerManager::Istance()->GetEntityByID(tel.Receiver);

		Discharge(receiver, tel);

		PriorityQueue.erase(PriorityQueue.begin());
	}
}


